package bscorp.appbase.activity;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.bean.TieBean;
import com.dou361.dialogui.listener.DialogUIItemListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import bscorp.appbase.AppManager;
import bscorp.appbase.R;
import bscorp.appbase.bmo.DeviceBmo;
import bscorp.appbase.bmo.OperateBmo;
import bscorp.appbase.bmo.OrderBmo;
import bscorp.appbase.model.Device;
import bscorp.appbase.model.Operate;
import bscorp.appbase.model.Order;
import bscorp.appbase.model.User;

public class AddOrderActivity extends AppCompatActivity {

    EditText edit_description;
    Button btn_add;
    TextView txt_device;
    private AddOrderTask mTask = null;
    private User mUser = AppManager.LOCAL_LOGINED_USER;
    private TieBean mTieBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_order);

        DialogUIUtils.init(getApplication());

        edit_description = (EditText) findViewById(R.id.edit_description);
        txt_device = (TextView) findViewById(R.id.txt_device);
        txt_device.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final List<TieBean> strings = new ArrayList<TieBean>();
                List<Device> devices = new DeviceBmo().getDevices();
                if (devices.size() == 0) {
                    DialogUIUtils.showToast("当前设备为空，请先添加设备");
                    return;
                }
                for (Device device : devices) {
                    TieBean tieBean = new TieBean(device.getName(), device.getId());
                    strings.add(tieBean);
                }
                DialogUIUtils.showSheet(AddOrderActivity.this, strings, "", Gravity.CENTER, true, true, new DialogUIItemListener() {
                    @Override
                    public void onItemClick(CharSequence text, int position) {
                        mTieBean = strings.get(position);
                        txt_device.setText(mTieBean.getTitle());
                    }
                }).show();
            }
        });
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptCreate();
            }
        });
    }

    public void attemptCreate() {
        // Store values at the time of the login attempt.
        String description = edit_description.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid email address.
        if (TextUtils.isEmpty(description)) {
            edit_description.setError(getString(R.string.error_field_required));
            focusView = edit_description;
            cancel = true;
        } else if (mTieBean == null) {
            focusView = txt_device;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            mTask = new AddOrderTask(description, mTieBean.getId(), mTieBean.getTitle());
            mTask.execute((Void) null);
        }
    }


    public class AddOrderTask extends AsyncTask<Void, Void, Boolean> {
        private final String aDescription;
        private final int aDeviceId;
        private final String aDeviceName;


        AddOrderTask(String description, int deviceId, String deviceName) {
            aDescription = description;
            aDeviceId = deviceId;
            aDeviceName = deviceName;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            Order order = new Order();
            order.setReportUserId(mUser.getId());
            order.setType(Order.ORDER_NEW);
            order.setTime(new Date());
            order.setDeviceId(aDeviceId);
            order.setDeviceName(aDeviceName);
            order.setDescription(aDescription);

            OrderBmo orderBmo = new OrderBmo();
            if (!orderBmo.saveOrderInfo(order)) {
                return false;
            }
            List<Order> nOrders = orderBmo.getOrderByReportUserIdAndType(mUser.getId() + "", Order.ORDER_NEW);
            if (nOrders.size() < 0) {
                return false;
            }
            Order nOrder = nOrders.get(nOrders.size() - 1);

            Operate operate = new Operate();
            operate.setOrderId(nOrder.getId());
            operate.setUser(mUser.getName());
            operate.setUserPhone(mUser.getPhone());
            operate.setDescription(aDescription);
            operate.setTime(order.getTime());
            operate.setResult("工单创建成功");

            return new OperateBmo().saveOperate(operate);
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mTask = null;
            if (success) {
                Toast.makeText(AddOrderActivity.this, "成功", Toast.LENGTH_SHORT).show();
                onBackPressed();
            } else {
                Toast.makeText(AddOrderActivity.this, "失败", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected void onCancelled() {
            mTask = null;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}
